﻿namespace wToggle.Platform.Data
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Threading.Tasks;

    using wToggle.Platform.Interfaces;

    using XPlatUtils;

    [DataContract]
    public sealed class Workspace : IEntity
    {
        public Workspace()
        {
            this.SetDefaults();
        }

        private void SetDefaults()
        {
            this.Tags = new List<Tag>();
            this.Clients = new List<Client>();
            this.Projects = new List<Project>();
        }

        [OnDeserializing]
        public void OnDeserializing(StreamingContext context)
        {
            this.SetDefaults();
        }

        [DataMember(Name = "id")]
        public ulong Id { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "premium")]
        public bool IsPremium { get; set; }

        [DataMember(Name = "admin")]
        public bool IsAdmin { get; set; }

        [DataMember(Name = "default_hourly_rate")]
        public uint DefaultHourlyRate { get; set; }

        [DataMember(Name = "default_currency")]
        public string DefaultCurrency { get; set; }

        [DataMember(Name = "only_admins_may_create_projects")]
        public bool OnlyAdminsMayCreateProjects { get; set; }

        [DataMember(Name = "only_admins_see_billable_rates")]
        public bool OnlyAdminsSeeBillableRates { get; set; }

        [DataMember(Name = "logo_url")]
        public string LogoUrl { get; set; }

        [DataMember(Name = "rounding")]
        public int Rounding { get; set; }

        [DataMember(Name = "rounding_minutes")]
        public int RoundingMinutes { get; set; }

        public IEnumerable<Tag> Tags { get; set; }

        public IEnumerable<Project> Projects { get; set; }

        public IEnumerable<Client> Clients { get; set; }

        public async Task<IEnumerable<Tag>> GetTags()
        {
            this.Tags = (await Toggly.GetTags(this.Id)).OrderBy(t => t.Name).ToArray();
            return this.Tags;
        }

        public async Task<IEnumerable<Project>> GetProjects()
        {
            this.Projects = (await Toggly.GetProjects(this.Id)).OrderBy(t => t.Name).ToArray();
            return this.Projects;
        }

        public async Task<IEnumerable<Client>> GetClients()
        {
            var provider = ServiceContainer.Resolve<IClientProvider>();

            this.Clients = await provider.GetClients(this.Id);
            return this.Clients;
        }

        public async Task LoadWorkspaceData()
        {
            await this.GetClients();
            await this.GetProjects();
            await this.GetTags();
        }
    }
}